<template>
  <div class="map">
    <div class="map-content" >
      <div class="map-chart" ref="mapChart"></div>
      <div class="scatter" :style="scatterStyle" ref="scatter" @mouseleave="leaveScatter">
        <div class="scatter-li"
             :class="{'scatterClick': canClickScatter}"
             v-for="(item, index) in scatter"
             :key="index"
             @click="handleMap(item)">{{item.companyName}}</div>
      </div>
      <div class="map-background" v-if="themeConfig.moduleTheme == 'flat' && isNeedMapBackground">
        <img src="./../../assets/images/module/map-background.png" alt="">
      </div>
    </div>
    <div class="map-menu" v-if="isMapMenu">
      <span class="menu-btn"
            @click="handleMenu(index, item)"
            :class="{'active': index == menuBtnName.length - 1}"
            v-for="(item, index) in menuBtnName" :key="index">
        <i class="border-i border-left" v-if="index > 0"></i>
        <i class="message">{{item.name}}</i>
        <i class="border-i border-right"></i>
        <i class="present"></i>
      </span>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import _ from 'lodash'
import * as utils from '../../utils/index'
import { cityArea } from '../../utils/mapCityArea'
import { provinceName } from '../../utils/provinceNameMap'
import { getMapData } from './../../utils/BmapData'
require('echarts-gl')
require('echarts/map/js/china.js')
export default {
  name: 'mapVue',
  props: {
    // 是否在选择地图的时候需要回调
    isCallback: {
      type: Boolean,
      default: false
    },
    // 是否使用2D绘图
    isUse2D: {
      type: Boolean,
      default: false
    },
    // 是否需要地图菜单
    isMapMenu: {
      type: Boolean,
      default: true
    },
    isNeedMapBackground: {
      type: Boolean,
      default: true
    },
    // 请求数据在外面
    isPropsData: {
      type: Boolean,
      default: false
    },
    // 地图数据
    mapData: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      scatter: [], // 标注信息列表
      scatterStyle: {},
      canClickScatter: false, // 能否点击进入下一级地图
      menuBtnName: [{ name: '全国' }], // 地图菜单按钮
      currentProvinceData: {}, // 当前省份数据
      provinceMapData: [], // 省份地图数据
      provinceId: '', // 省份id
      cityId: '', // 城市id
      areaId: '', // 区Id
      currentCityData: {}, // 当前城市数据
      cityMapData: [], // 城市地图数据
      areaData: [],
      mapChart: '',
      loading: false,
      systemIdentification: ''
    }
  },
  computed: {
    organId () {
      return this.$store.state.organId
    },
    themeConfig () {
      return this.$store.state.themeConfig
    }
  },
  methods: {
    showTips (data) {
      this.$emit('showTips', data)
    },
    // 点击导航
    handleMenu (index, item) {
      if (index < 2) {
        this.canClickScatter = true
      }
      if (index === this.menuBtnName.length - 1 || this.loading) {
        return false
      }
      switch (index) {
        case 0: this.provinceId = ''
          this.cityId = ''
          this.areaId = ''
          this.changesCompany()
          this.getProvince()
          break
        case 1: if (cityArea[this.menuBtnName[1].name]) {
          this.areaId = ''
          this.changesCompany()
          this.cityHandle(this.currentCityData, this.cityMapData)
        } else {
          this.cityId = ''
          this.areaId = ''
          this.changesCompany()
          this.provinceHandle(this.currentProvinceData, this.provinceMapData)
        }
          break
        case 2: this.areaId = ''
          this.changesCompany()
          this.cityHandle(this.currentCityData, this.cityMapData)
          break
      }
    },
    // 点击地图上的名字弹窗
    handleMap (item) {
      if (!this.canClickScatter || this.loading) {
        return false
      }
      switch (this.menuBtnName.length) {
        case 1: this.companyClickFn(item.provinceId, item.companyName)
          break
        case 2: if (item.cityId) {
          this.cityClick(item.cityId, item.companyName)
        } else {
          this.areaClick(item.areaId, item.companyName)
        }
          break
        case 3: this.areaClick(item.areaId, item.companyName)
          break
        case 4: this.areaClick(item.areaId, item.companyName)
          break
      }
    },
    // 鼠标移出弹窗
    leaveScatter () {
      this.scatterStyle = {
        display: 'none'
      }
    },
    // 获取省份数据
    getProvince () {
      if (this.mapChart !== '' && this.mapChart.isDisposed) {
        this.mapChart.off('mousemove')
        this.mapChart.clear()
      }
      this.menuBtnName = [{ name: '全国' }]
      this.mapApi.getProvinceList({
        organId: this.organId
      }).then((res) => {
        let data = []
        if (res.data.code === '0') {
          res.data.data.regionData.forEach(item => {
            data.push({
              provinceId: item.regionId,
              provinceName: item.regionIdName,
              communityNums: item.communityNums
            })
          })
        } else {
          this.showTips('请求失败，点击确认继续刷新')
        }
        this.countryData(data)
      }, (res) => {
        this.mapChart = echarts.init(this.$refs.mapChart)
        this.mapChart.setOption(utils.getMapOption([]).option)
        this.showTips('请求失败，点击确认继续刷新')
      })
    },
    countryData (data) {
      if (this.mapChart === '') {
        this.mapChart = echarts.init(this.$refs.mapChart)
      }
      let provinceMessage = this.systemIdentification === 'android' ? utils.getMapOption2D(data) : this.isUse2D ? utils.getMapOption2D(data) : utils.getMapOption(data)
      this.mapChart.setOption(provinceMessage.option)
      this.provinceArr = provinceMessage.arr
      let scatterDom
      let that = this
      if (this.isMapMenu) {
        that.canClickScatter = true
      } else {
        that.canClickScatter = false
      }
      this.mapChart.off('mousemove')
      this.mapChart.on('mousemove', function (params) {
        scatterDom = []
        for (let i = 0; i < that.provinceArr.length; i++) {
          if (params.name === that.provinceArr[i]) {
            // companyId, 分公司Id,现在不需要，type区分点击分公司还是点击省份
            scatterDom.push({ companyName: params.name + ': ' + data[i].communityNums, provinceId: data[i].provinceId, type: 1 })
            that.scatter = scatterDom
            that.scatterStyle = {
              left: params.event.offsetX + 'px',
              top: params.event.offsetY + 'px',
              display: 'block'
            }
            break
          } else {
            that.scatterStyle = {
              display: 'none'
            }
          }
        }
      })
    },
    // 点击省份
    companyClickFn (provinceId, name) {
      if (!this.canClickScatter || this.loading) {
        return false
      }
      this.loading = true
      this.provinceId = provinceId
      this.cityId = ''
      this.areaId = ''
      this.changesCompany()
      name = name.indexOf(':') > -1 ? name.substring(0, name.indexOf(':')) : name
      //  获取省份下的城市项目数
      this.mapApi.getProvinceData({ organId: this.organId, provinceId: provinceId }).then((res) => {
        if (res.data.code === '0') {
          this.provinceData(provinceId, name, res.data.data)
        } else {
          this.showTips('请求失败，点击确认继续刷新')
        }
        this.scatterStyle = {
          display: 'none'
        }
        this.provinceData(provinceId, name, '')
      }, (res) => {
        this.showTips('请求失败，点击确认继续刷新')
        this.scatterStyle = {
          display: 'none'
        }
        this.provinceData(provinceId, name, '')
      })
    },
    // type 为propData时候,数据是外面传进来
    provinceData (provinceId, name, resData, type) {
      let datas
      let provinceCity = []
      let citys = []
      if (resData !== '') {
        if (cityArea[name]) {
          if (resData.regionData.length > 0) {
            this.loading = false
            this.cityClick(resData.regionData[0].regionId, name)
          } else {
            this.showTips('该区域暂无数据')
          }
          return false
        }
        resData.regionData.forEach(item => {
          citys.push({
            cityId: type === 'propData' ? item.cityId : item.regionId,
            cityName: type === 'propData' ? item.cityName : item.regionIdName,
            communityNums: item.communityNums
          })
        })
        let provinceCityArea = ''
        provinceCityArea = provinceName[name]
        resData.regionAllName.forEach(item => {
          provinceCity.push(provinceCityArea + ',' + item)
        })
      }
      datas = {
        provincesName: name,
        provinceId: provinceId,
        citys: citys
      }
      let simulationParams = {
        mapData: provinceCity,
        type: 'province',
        mapName: name,
        callback: this.provinceHandle,
        callbackData: datas
      }
      getMapData(simulationParams)
    },
    // 点击地图省份后处理数据
    provinceHandle (data, mapData) {
      let that = this
      that.provinceMapData = mapData
      that.currentProvinceData = data
      that.loading = false
      this.scatterStyle = {
        display: 'none'
      }
      // that.menuBtnIndex = 1
      that.menuBtnName = [{ name: '全国' }, { name: data.provincesName, id: data.provinceId }]
      let showArr = []
      let nameArr = []
      let nameStr = ''
      data.citys.forEach(dataItem => {
        nameArr.push(dataItem.cityName)
      })
      mapData.forEach(item => {
        nameStr = item.properties.name.indexOf(':') > -1 ? item.properties.name.substring(0, item.properties.name.indexOf(':')) : item.properties.name
        if (nameArr.indexOf(nameStr) > -1) {
          showArr.push({
            cityId: data.citys[nameArr.indexOf(nameStr)].cityId,
            cityName: item.properties.name,
            communityNums: data.citys[nameArr.indexOf(nameStr)].communityNums
          })
        }
      })
      data.citys = showArr
      if (this.mapChart !== '' && this.mapChart.isDisposed) {
        this.mapChart.off('mousemove')
        this.mapChart.clear()
      }
      if (this.mapChart === '') {
        this.mapChart = echarts.init(this.$refs.mapChart)
      }
      let cityMessage = this.systemIdentification === 'android' ? utils.drawing2D(data) : this.isUse2D ? utils.drawing2D(data) : utils.drawing(data)
      this.mapChart.setOption(cityMessage)
      showArr = null
      nameArr = null
      nameStr = null
      let scatterDom
      this.mapChart.off('click')
      this.mapChart.off('mousemove')
      if (that.isMapMenu) {
        that.canClickScatter = true
      } else {
        that.canClickScatter = false
      }
      this.mapChart.on('mousemove', function (params) {
        scatterDom = []
        for (let i = 0; i < data.citys.length; i++) {
          if (params.name === data.citys[i].cityName) {
            let showName = params.name.indexOf(':') > -1 ? params.name.substring(0, params.name.indexOf(':')) : params.name
            scatterDom.push({ companyName: showName + ': ' + data.citys[i].communityNums, cityId: data.citys[i].cityId })
            that.scatter = scatterDom
            that.scatterStyle = {
              left: params.event.offsetX + 'px',
              top: params.event.offsetY + 'px',
              display: 'block'
            }
            break
          } else {
            that.scatterStyle = {
              display: 'none'
            }
          }
        }
      })
    },
    // 点击城市
    cityClick (cityId, name) {
      if (!this.canClickScatter || this.loading) {
        return false
      }
      this.loading = true
      let cityName = name.indexOf(':') > -1 ? name.substring(0, name.indexOf(':')) : name
      this.cityId = cityId
      this.areaId = ''
      this.changesCompany()
      this.mapApi.getCityData({ organId: this.organId, provinceId: this.provinceId, cityId: cityId }).then((res) => {
        if (res.data.code === '0') {
          let provinceCityArea = ''
          this.menuBtnName.forEach((item, index) => {
            if (index > 0) {
              provinceCityArea = provinceCityArea === '' ? provinceName[item.name] : provinceCityArea + ',' + item.name
            }
          })
          provinceCityArea = provinceCityArea + ',' + cityName
          this.cityDate(cityId, cityName, res.data.data, provinceCityArea)
        } else {
          this.showTips('请求失败，点击确认继续刷新')
          this.cityDate(cityId, cityName, '', '')
        }
        this.scatterStyle = {
          display: 'none'
        }
      }, res => {
        this.showTips('请求失败，点击确认继续刷新')
        this.scatterStyle = {
          display: 'none'
        }
        this.cityDate(cityId, cityName, '', '')
      })
    },
    cityDate (cityId, cityName, resData, provinceCityArea, dataType) {
      let cityAllArea = []
      let areas = []
      if (resData !== '') {
        cityAllArea.push(provinceCityArea)
        resData.regionAllName.forEach(item => {
          cityAllArea.push(provinceCityArea + ',' + item)
        })
        resData.regionData.forEach(item => {
          areas.push({
            areaId: item.regionId,
            areaName: dataType === 'outerData' ? item.regionName : item.regionIdName,
            communityNums: item.communityNums
          })
        })
      }
      let datas = {
        cityName: cityName,
        cityId: cityId,
        areas: areas,
        dataType: dataType
      }
      let simulationParams = {
        mapData: cityAllArea,
        type: 'city',
        mapName: cityName,
        callback: this.cityHandle,
        callbackData: datas
      }
      getMapData(simulationParams)
    },
    // 处理城市下的区数据
    cityHandle (data, mapData, isNotArea) {
      if (mapData.length === 0 && data.dataType === 'outerData') {
        this.handleMapData('province')
        return false
      }
      let that = this
      that.cityMapData = mapData
      that.currentCityData = data
      that.loading = false
      this.scatterStyle = {
        display: 'none'
      }
      if (cityArea[data.cityName]) {
        that.menuBtnName.splice(2)
        that.menuBtnName[1] = { name: data.cityName, id: data.cityId }
      } else {
        that.menuBtnName.splice(3)
        that.menuBtnName[2] = { name: data.cityName, id: data.cityId }
      }
      let showArr = []
      let nameArr = []
      let nameStr = ''
      let allCommunityNums = 0
      data.areas.forEach(dataItem => {
        if (isNotArea) {
          allCommunityNums += Number(dataItem.communityNums)
        }
        nameArr.push(dataItem.areaName)
      })
      mapData.forEach(item => {
        nameStr = item.properties.name.indexOf(':') > -1 ? item.properties.name.substring(0, item.properties.name.indexOf(':')) : item.properties.name
        if (nameArr.indexOf(nameStr) > -1) {
          showArr.push({
            areaId: data.areas[nameArr.indexOf(nameStr)].areaId,
            areaName: item.properties.name,
            communityNums: data.areas[nameArr.indexOf(nameStr)].communityNums
          })
        }
      })
      if (isNotArea) {
        showArr.push({
          areaId: data.cityId,
          areaName: data.cityName,
          communityNums: allCommunityNums
        })
      }
      data.areas = showArr
      this.areaData = data
      if (this.mapChart !== '' && this.mapChart.isDisposed) {
        this.mapChart.off('mousemove')
        this.mapChart.clear()
      }
      if (this.mapChart === '') {
        this.mapChart = echarts.init(this.$refs.mapChart)
      }
      let cityMessage = this.systemIdentification === 'android' ? utils.drawCity2D(data) : this.isUse2D ? utils.drawCity2D(data) : utils.drawCity(data)
      this.mapChart.setOption(cityMessage)
      showArr = null
      nameArr = null
      nameStr = null
      let scatterDom
      if (isNotArea) {
        that.canClickScatter = false
      } else {
        that.canClickScatter = true
      }
      if (that.isMapMenu) {
        that.canClickScatter = true
      } else {
        that.canClickScatter = false
      }
      this.mapChart.on('mousemove', function (params) {
        scatterDom = []
        for (let i = 0; i < data.areas.length; i++) {
          if (params.name === data.areas[i].areaName) {
            let showName = params.name.indexOf(':') > -1 ? params.name.substring(0, params.name.indexOf(':')) : params.name
            scatterDom.push({ companyName: showName + ': ' + data.areas[i].communityNums, areaId: data.areas[i].areaId })
            that.scatter = scatterDom
            that.scatterStyle = {
              left: params.event.offsetX + 'px',
              top: params.event.offsetY + 'px',
              display: 'block'
            }
            break
          } else {
            that.scatterStyle = {
              display: 'none'
            }
          }
        }
      })
    },
    // 点击区的操作
    areaClick (areaId, name) {
      let that = this
      this.loading = false
      let data = _.cloneDeep(this.areaData)
      let areaName = name.substring(0, name.indexOf(':'))
      if (name.substring(0, name.indexOf(':')) === this.menuBtnName[this.menuBtnName.length - 1].name) {
        return false
      }
      that.areaId = areaId
      that.changesCompany()
      if (cityArea[this.menuBtnName[1].name]) {
        this.menuBtnName = [...this.menuBtnName.slice(0, 2), ...[{ name: areaName }]]
      } else {
        this.menuBtnName = [...this.menuBtnName.slice(0, 3), ...[{ name: areaName }]]
      }
      data.currentAreaName = areaName
      if (this.mapChart !== '' && this.mapChart.isDisposed) {
        this.mapChart.off('mousemove')
        this.mapChart.clear()
      }
      let cityMessage = this.systemIdentification === 'android' ? utils.drawCity2D(data) : this.isUse2D ? utils.drawCity2D(data) : utils.drawCity(data)
      this.mapChart.setOption(cityMessage)
      let scatterDom
      this.mapChart.off('mouseover')
      this.mapChart.off('mousemove')
      that.canClickScatter = true
      this.mapChart.on('mousemove', function (params) {
        scatterDom = []
        for (let i = 0; i < data.areas.length; i++) {
          if (params.name === data.areas[i].areaName) {
            let showName = params.name.indexOf(':') > -1 ? params.name.substring(0, params.name.indexOf(':')) : params.name
            scatterDom.push({ companyName: showName + ': ' + data.areas[i].communityNums, areaId: data.areas[i].areaId })
            that.scatter = scatterDom
            that.scatterStyle = {
              left: params.event.offsetX + 'px',
              top: params.event.offsetY + 'px',
              display: 'block'
            }
            break
          } else {
            that.scatterStyle = {
              display: 'none'
            }
          }
        }
      })
    },
    // 获取公司信息回调
    changesCompany () {
      if (this.isCallback) {
        this.$emit('changeMap', { provinceId: this.provinceId, cityId: this.cityId, areaId: this.areaId })
      }
    },
    // 查看是否是安卓浏览器还是电脑浏览器
    checkBrowser () {
      let regex = RegExp('android', 'i')
      if (regex.test(window.navigator.userAgent)) {
        this.systemIdentification = 'android'
      } else {
        this.systemIdentification = ''
      }
    },
    handleMapData (type) {
      // 调用全国数据
      let data = _.cloneDeep(this.mapData)
      if (data.length === 0) {
        this.countryData([])
      } else if (data.length > 1) {
        this.countryData(data)
      } else {
        if (data[0].regionData.length === 0) {
          let name = utils.dislodge([data[0].provinceName])[0]
          let provinceId = data[0].provinceId
          this.provinceData(provinceId, name, '', 'propData')
        } else if (data[0].regionData.length > 1 || type === 'province') {
          let name = utils.dislodge([data[0].provinceName])[0]
          let provinceId = data[0].provinceId
          this.provinceData(provinceId, name, data[0], 'propData')
        } else if (data[0].regionData.length === 1) {
          let provinceCityArea = data[0].provinceName + data[0].regionData[0].cityName
          this.cityDate(data[0].regionData[0].cityId, data[0].regionData[0].cityName, data[0].regionData[0], provinceCityArea, 'outerData')
        }
      }
    },
    resizeChart () {
      this.mapChart.resize()
    }
  },
  created () {
    this.checkBrowser()
  },
  watch: {
    organId (val) {
      this.$nextTick(function () {
        if (!this.isPropsData) {
          this.getProvince()
        }
      })
    },
    mapData (val) {
      this.handleMapData()
    }
  }
}
</script>

<style lang="scss">
.map {
  width: 100%;
  height: 100%;
  position: relative;
  .map-content {
    width: 100%;
    height: 100%;
    position: relative;
    .map-chart {
      width: 100%;
      height: 100%;
      position: relative;
      z-index: 10;
    }
    .scatter {
      display: none;
      padding: 10px 11px;
      background: rgba(7, 23, 62, 0.8);
      border:1px solid #1072e2;
      position: absolute;
      margin: 0;
      white-space: nowrap;
      transform: translate(-50%, -50%);
      font-size: 14px;
      line-height: 20px;
      border-radius: 4px;
      color: #fff;
      z-index: 50;
      max-height: 95px;
      overflow-y: auto;
      overflow-x: hidden;
      &::-webkit-scrollbar {
        background-color: transparent;
        width: 8px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: #0f4199;
        border-radius: 8px;
      }
      &::-webkit-scrollbar-button {
        background-color: transparent;
        height:5px;
      }
      &::-webkit-scrollbar-corner {
        background-color: #fff;
      }
      &::-webkit-scrollbar-arrow-color {
        background-color: #fff;
      }
      .scatter-li {
        &.scatterClick {
          cursor: pointer;
          &:hover {
            color: #a0c9fe;
            background: rgba(22, 112, 218, 0.2);
          }
        }
        margin: 0 0 5px 0;
        padding: 0 3px;
        &:last-of-type {
          margin: 0;
        }
      }
    }
    .map-background {
      width: 100%;
      position: absolute;
      bottom: 0;
      left: 0;
      img {
        width: 100%;
      }
    }
  }
  .map-menu {
    width: calc(100% - 20px);
    height: 40px;
    font-size: 14px;
    text-align: left;
    position: absolute;
    left: 10px;
    top: 0;
    z-index: 20;
    .menu-btn {
      display: inline-block;
      position: relative;
      height: 40px;
      box-sizing: border-box;
      padding: 0 10px;
      color:#fff;
      border-top: 1px solid #4f85fd;
      border-bottom: 1px solid #4f85fd;
      margin-right: 16px;
      cursor: pointer;
      vertical-align: top;
      &:last-of-type {
        cursor: inherit;
      }
      &:first-of-type {
        border-left: 1px solid #4f85fd;
        padding-left: 11px;
      }
      .message {
        display: inline-block;
        line-height: 40px;
      }
      .border-i {
        display: inline-block;
        width: 13px;
        height: 40px;
        position: absolute;
        top:-1px;
      }
      .border-left {
        left: -11px;
        background: url(../../assets/images/module/border-left.png) no-repeat center;
        background-size: 100%;
      }
      .border-right {
        right: -11px;
        z-index: 10;
        background: url(../../assets/images/module/border-right.png) no-repeat center;
        background-size: 100%;
      }
      .present {
        width: 26px;
        height: 26px;
        display: none;
        position: absolute;
        left: 50%;
        top:24px;
        transform: translateX(-50%);
        z-index: 20;
        background: url(../../assets/images/module/present.png) no-repeat center;
        background-size: 100%;
      }
      &.active {
        .present {
          display: inline-block;
        }
      }
    }
  }
}
</style>
